package com.zhaoyang.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 赵扬
 * @time 2020/4/28 13:09
 * <p>
 * 过滤器 过滤掉未登录用户
 */
// TODO >> 先注释 避免 浏览器检测到该服务器正在将指向此网址的请求无限循环重定向。
@WebFilter(servletNames = {"/systemServlet", "/attendanceServlet", "/clazzServlet",
        "/courseServlet", "/leaveServlet", "/photoServlet", "/scoreServlet",
        "/selectedCourseServlet", "/studentServlet", "/teacherServlet"},
        urlPatterns = {"/view/teacherList.jsp","/view/studentList.jsp"})
public class LoginFilter implements Filter {
    /**
     * 服务器正常关闭后,Filter对象会被销毁,destory会自动执行,只执行一次 用于释放资源
     */
    public void destroy() {
    }

    /**
     * 每次请求被拦截资源时,会执行.执行多次
     *
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Object user = request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect("/index.jsp");
            return;
        } else {
            chain.doFilter(request, response);
        }
    }

    /**
     * 每次Filter启动后,会创建Filter对象,然后调用init方法,只执行一次 用于加载资源
     *
     * @param config
     * @throws ServletException
     */
    public void init(FilterConfig config) throws ServletException {

    }

}
